home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / lib / ruby / 1.8 / optparse.rb < prev    next >
Encoding:
Ruby Source  |  2009-02-20  |  47.1 KB  |  1,797 lines

  1. #
  2. # optparse.rb - command-line option analysis with the OptionParser class.
  3. # Author:: Nobu Nakada
  4. # Documentation:: Nobu Nakada and Gavin Sinclair.
  5. #
  6. # See OptionParser for documentation. 
  7. #
  8.  
  9.  
  10. # == Developer Documentation (not for RDoc output) 
  11. # === Class tree
  12. #
  13. # - OptionParser:: front end
  14. # - OptionParser::Switch:: each switches
  15. # - OptionParser::List:: options list
  16. # - OptionParser::ParseError:: errors on parsing
  17. #   - OptionParser::AmbiguousOption
  18. #   - OptionParser::NeedlessArgument
  19. #   - OptionParser::MissingArgument
  20. #   - OptionParser::InvalidOption
  21. #   - OptionParser::InvalidArgument
  22. #     - OptionParser::AmbiguousArgument
  23. #
  24. # === Object relationship diagram
  25. #
  26. #   +--------------+
  27. #   | OptionParser |<>-----+
  28. #   +--------------+       |                      +--------+
  29. #                          |                    ,-| Switch |
  30. #        on_head -------->+---------------+    /  +--------+
  31. #        accept/reject -->| List          |<|>-
  32. #                         |               |<|>-  +----------+
  33. #        on ------------->+---------------+    `-| argument |
  34. #                           :           :        |  class   |
  35. #                         +---------------+      |==========|
  36. #        on_tail -------->|               |      |pattern   |
  37. #                         +---------------+      |----------|
  38. #   OptionParser.accept ->| DefaultList   |      |converter |
  39. #                reject   |(shared between|      +----------+
  40. #                         | all instances)|
  41. #                         +---------------+
  42. #
  43. # == OptionParser
  44. #
  45. # === Introduction
  46. #
  47. # OptionParser is a class for command-line option analysis.  It is much more
  48. # advanced, yet also easier to use, than GetoptLong, and is a more Ruby-oriented
  49. # solution.
  50. #
  51. # === Features
  52. # 1. The argument specification and the code to handle it are written in the
  53. #    same place.
  54. # 2. It can output an option summary; you don't need to maintain this string
  55. #    separately.
  56. # 3. Optional and mandatory arguments are specified very gracefully.
  57. # 4. Arguments can be automatically converted to a specified class.
  58. # 5. Arguments can be restricted to a certain set.
  59. #
  60. # All of these features are demonstrated in the examples below.
  61. #
  62. # === Minimal example
  63. #
  64. #   require 'optparse'
  65. #
  66. #   options = {}
  67. #   OptionParser.new do |opts|
  68. #     opts.banner = "Usage: example.rb [options]"
  69. #
  70. #     opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
  71. #       options[:verbose] = v
  72. #     end
  73. #   end.parse!
  74. #
  75. #   p options
  76. #   p ARGV
  77. #
  78. # === Complete example
  79. #
  80. # The following example is a complete Ruby program.  You can run it and see the
  81. # effect of specifying various options.  This is probably the best way to learn
  82. # the features of +optparse+.
  83. #
  84. #   require 'optparse'
  85. #   require 'optparse/time'
  86. #   require 'ostruct'
  87. #   require 'pp'
  88. #   
  89. #   class OptparseExample
  90. #   
  91. #     CODES = %w[iso-2022-jp shift_jis euc-jp utf8 binary]
  92. #     CODE_ALIASES = { "jis" => "iso-2022-jp", "sjis" => "shift_jis" }
  93. #   
  94. #     #
  95. #     # Return a structure describing the options.
  96. #     #
  97. #     def self.parse(args)
  98. #       # The options specified on the command line will be collected in *options*.
  99. #       # We set default values here.
  100. #       options = OpenStruct.new
  101. #       options.library = []
  102. #       options.inplace = false
  103. #       options.encoding = "utf8"
  104. #       options.transfer_type = :auto
  105. #       options.verbose = false
  106. #       
  107. #       opts = OptionParser.new do |opts|
  108. #         opts.banner = "Usage: example.rb [options]"
  109. #       
  110. #         opts.separator ""
  111. #         opts.separator "Specific options:"
  112. #       
  113. #         # Mandatory argument.
  114. #         opts.on("-r", "--require LIBRARY",
  115. #                 "Require the LIBRARY before executing your script") do |lib|
  116. #           options.library << lib
  117. #         end
  118. #       
  119. #         # Optional argument; multi-line description.
  120. #         opts.on("-i", "--inplace [EXTENSION]",
  121. #                 "Edit ARGV files in place",
  122. #                 "  (make backup if EXTENSION supplied)") do |ext|
  123. #           options.inplace = true
  124. #           options.extension = ext || ''
  125. #           options.extension.sub!(/\A\.?(?=.)/, ".")  # Ensure extension begins with dot.
  126. #         end
  127. #       
  128. #         # Cast 'delay' argument to a Float.
  129. #         opts.on("--delay N", Float, "Delay N seconds before executing") do |n|
  130. #           options.delay = n
  131. #         end
  132. #       
  133. #         # Cast 'time' argument to a Time object.
  134. #         opts.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time|
  135. #           options.time = time
  136. #         end
  137. #       
  138. #         # Cast to octal integer.
  139. #         opts.on("-F", "--irs [OCTAL]", OptionParser::OctalInteger,
  140. #                 "Specify record separator (default \\0)") do |rs|
  141. #           options.record_separator = rs
  142. #         end
  143. #       
  144. #         # List of arguments.
  145. #         opts.on("--list x,y,z", Array, "Example 'list' of arguments") do |list|
  146. #           options.list = list
  147. #         end
  148. #       
  149. #         # Keyword completion.  We are specifying a specific set of arguments (CODES
  150. #         # and CODE_ALIASES - notice the latter is a Hash), and the user may provide
  151. #         # the shortest unambiguous text.
  152. #         code_list = (CODE_ALIASES.keys + CODES).join(',')
  153. #         opts.on("--code CODE", CODES, CODE_ALIASES, "Select encoding",
  154. #                 "  (#{code_list})") do |encoding|
  155. #           options.encoding = encoding
  156. #         end
  157. #       
  158. #         # Optional argument with keyword completion.
  159. #         opts.on("--type [TYPE]", [:text, :binary, :auto],
  160. #                 "Select transfer type (text, binary, auto)") do |t|
  161. #           options.transfer_type = t
  162. #         end
  163. #       
  164. #         # Boolean switch.
  165. #         opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
  166. #           options.verbose = v
  167. #         end
  168. #       
  169. #         opts.separator ""
  170. #         opts.separator "Common options:"
  171. #       
  172. #         # No argument, shows at tail.  This will print an options summary.
  173. #         # Try it and see!
  174. #         opts.on_tail("-h", "--help", "Show this message") do
  175. #           puts opts
  176. #           exit
  177. #         end
  178. #       
  179. #         # Another typical switch to print the version.
  180. #         opts.on_tail("--version", "Show version") do
  181. #           puts OptionParser::Version.join('.')
  182. #           exit
  183. #         end
  184. #       end
  185. #       
  186. #       opts.parse!(args)
  187. #       options
  188. #     end  # parse()
  189. #   
  190. #   end  # class OptparseExample
  191. #   
  192. #   options = OptparseExample.parse(ARGV)
  193. #   pp options
  194. #
  195. # === Further documentation
  196. #
  197. # The above examples should be enough to learn how to use this class.  If you
  198. # have any questions, email me (gsinclair@soyabean.com.au) and I will update
  199. # this document.
  200. #
  201. class OptionParser
  202.   # :stopdoc:
  203.   RCSID = %w$Id: optparse.rb 22469 2009-02-20 11:43:35Z shyouhei $[1..-1].each {|s| s.freeze}.freeze
  204.   Version = (RCSID[1].split('.').collect {|s| s.to_i}.extend(Comparable).freeze if RCSID[1])
  205.   LastModified = (Time.gm(*RCSID[2, 2].join('-').scan(/\d+/).collect {|s| s.to_i}) if RCSID[2])
  206.   Release = RCSID[2]
  207.  
  208.   NoArgument = [NO_ARGUMENT = :NONE, nil].freeze
  209.   RequiredArgument = [REQUIRED_ARGUMENT = :REQUIRED, true].freeze
  210.   OptionalArgument = [OPTIONAL_ARGUMENT = :OPTIONAL, false].freeze
  211.   # :startdoc:
  212.  
  213.   #
  214.   # Keyword completion module.  This allows partial arguments to be specified
  215.   # and resolved against a list of acceptable values.
  216.   #
  217.   module Completion
  218.     def complete(key, icase = false, pat = nil)
  219.       pat ||= Regexp.new('\A' + Regexp.quote(key).gsub(/\w+\b/, '\&\w*'),
  220.                          icase)
  221.       canon, sw, k, v, cn = nil
  222.       candidates = []
  223.       each do |k, *v|
  224.         (if Regexp === k
  225.            kn = nil
  226.            k === key
  227.          else
  228.            kn = defined?(k.id2name) ? k.id2name : k
  229.            pat === kn
  230.          end) or next
  231.         v << k if v.empty?
  232.         candidates << [k, v, kn]
  233.       end
  234.       candidates = candidates.sort_by {|k, v, kn| kn.size}
  235.       if candidates.size == 1
  236.         canon, sw, * = candidates[0]
  237.       elsif candidates.size > 1
  238.         canon, sw, cn = candidates.shift
  239.         candidates.each do |k, v, kn|
  240.           next if sw == v
  241.           if String === cn and String === kn
  242.             if cn.rindex(kn, 0)
  243.               canon, sw, cn = k, v, kn
  244.               next
  245.             elsif kn.rindex(cn, 0)
  246.               next
  247.             end
  248.           end
  249.           throw :ambiguous, key
  250.         end
  251.       end
  252.       if canon
  253.         block_given? or return key, *sw
  254.         yield(key, *sw)
  255.       end
  256.     end
  257.  
  258.     def convert(opt = nil, val = nil, *)
  259.       val
  260.     end
  261.   end
  262.  
  263.  
  264.   #
  265.   # Map from option/keyword string to object with completion.
  266.   #
  267.   class OptionMap < Hash
  268.     include Completion
  269.   end
  270.  
  271.  
  272.   #
  273.   # Individual switch class.  Not important to the user.
  274.   #
  275.   # Defined within Switch are several Switch-derived classes: NoArgument,
  276.   # RequiredArgument, etc. 
  277.   #
  278.   class Switch
  279.     attr_reader :pattern, :conv, :short, :long, :arg, :desc, :block
  280.  
  281.     #
  282.     # Guesses argument style from +arg+.  Returns corresponding
  283.     # OptionParser::Switch class (OptionalArgument, etc.).
  284.     #
  285.     def self.guess(arg)
  286.       case arg
  287.       when ""
  288.         t = self
  289.       when /\A=?\[/
  290.         t = Switch::OptionalArgument
  291.       when /\A\s+\[/
  292.         t = Switch::PlacedArgument
  293.       else
  294.         t = Switch::RequiredArgument
  295.       end
  296.       self >= t or incompatible_argument_styles(arg, t)
  297.       t
  298.     end
  299.  
  300.     def self.incompatible_argument_styles(arg, t)
  301.       raise ArgumentError, "#{arg}: incompatible argument styles\n  #{self}, #{t}"
  302.     end
  303.  
  304.     def self.pattern
  305.       NilClass
  306.     end
  307.  
  308.     def initialize(pattern = nil, conv = nil,
  309.                    short = nil, long = nil, arg = nil,
  310.                    desc = ([] if short or long), block = Proc.new)
  311.       raise if Array === pattern
  312.       @pattern, @conv, @short, @long, @arg, @desc, @block =
  313.         pattern, conv, short, long, arg, desc, block
  314.     end
  315.  
  316.     #
  317.     # Parses +arg+ and returns rest of +arg+ and matched portion to the
  318.     # argument pattern. Yields when the pattern doesn't match substring.
  319.     #
  320.     def parse_arg(arg)
  321.       pattern or return nil, arg
  322.       unless m = pattern.match(arg)
  323.         yield(InvalidArgument, arg)
  324.         return arg, nil
  325.       end
  326.       if String === m
  327.         m = [s = m]
  328.       else
  329.         m = m.to_a
  330.         s = m[0]
  331.         return nil, m unless String === s
  332.       end
  333.       raise InvalidArgument, arg unless arg.rindex(s, 0)
  334.       return nil, m if s.length == arg.length
  335.       yield(InvalidArgument, arg) # didn't match whole arg
  336.       return arg[s.length..-1], m
  337.     end
  338.     private :parse_arg
  339.  
  340.     #
  341.     # Parses argument, converts and returns +arg+, +block+ and result of
  342.     # conversion. Yields at semi-error condition instead of raising an
  343.     # exception.
  344.     #
  345.     def conv_arg(arg, val = nil)
  346.       if conv
  347.         val = conv.call(*val)
  348.       else
  349.         val = proc {|val| val}.call(*val)
  350.       end
  351.       return arg, block, val
  352.     end
  353.     private :conv_arg
  354.  
  355.     #
  356.     # Produces the summary text. Each line of the summary is yielded to the
  357.     # block (without newline).
  358.     #
  359.     # +sdone+::  Already summarized short style options keyed hash.
  360.     # +ldone+::  Already summarized long style options keyed hash.
  361.     # +width+::  Width of left side (option part). In other words, the right
  362.     #            side (description part) starts after +width+ columns.
  363.     # +max+::    Maximum width of left side -> the options are filled within
  364.     #            +max+ columns.
  365.     # +indent+:: Prefix string indents all summarized lines.
  366.     #
  367.     def summarize(sdone = [], ldone = [], width = 1, max = width - 1, indent = "")
  368.       sopts, lopts, s = [], [], nil
  369.       @short.each {|s| sdone.fetch(s) {sopts << s}; sdone[s] = true} if @short
  370.       @long.each {|s| ldone.fetch(s) {lopts << s}; ldone[s] = true} if @long
  371.       return if sopts.empty? and lopts.empty? # completely hidden
  372.  
  373.       left = [sopts.join(', ')]
  374.       right = desc.dup
  375.  
  376.       while s = lopts.shift
  377.         l = left[-1].length + s.length
  378.         l += arg.length if left.size == 1 && arg
  379.         l < max or sopts.empty? or left << ''
  380.         left[-1] << if left[-1].empty? then ' ' * 4 else ', ' end << s
  381.       end
  382.  
  383.       left[0] << arg if arg
  384.       mlen = left.collect {|s| s.length}.max.to_i
  385.       while mlen > width and l = left.shift
  386.         mlen = left.collect {|s| s.length}.max.to_i if l.length == mlen
  387.         yield(indent + l)
  388.       end
  389.  
  390.       while begin l = left.shift; r = right.shift; l or r end
  391.         l = l.to_s.ljust(width) + ' ' + r if r and !r.empty?
  392.         yield(indent + l)
  393.       end
  394.  
  395.       self
  396.     end
  397.  
  398.     def add_banner(to)  # :nodoc:
  399.       unless @short or @long
  400.         s = desc.join
  401.         to << " [" + s + "]..." unless s.empty?
  402.       end
  403.       to
  404.     end
  405.  
  406.     def match_nonswitch?(str) # :nodoc:
  407.       @pattern =~ str unless @short or @long
  408.     end
  409.  
  410.     #
  411.     # Main name of the switch.
  412.     #
  413.     def switch_name
  414.       (long.first || short.first).sub(/\A-+(?:\[no-\])?/, '')
  415.     end
  416.  
  417.     #
  418.     # Switch that takes no arguments.
  419.     #
  420.     class NoArgument < self
  421.  
  422.       #
  423.       # Raises an exception if any arguments given.
  424.       #
  425.       def parse(arg, argv)
  426.         yield(NeedlessArgument, arg) if arg
  427.         conv_arg(arg)
  428.       end
  429.  
  430.       def self.incompatible_argument_styles(*)
  431.       end
  432.  
  433.       def self.pattern
  434.         Object
  435.       end
  436.     end
  437.  
  438.     #
  439.     # Switch that takes an argument.
  440.     #
  441.     class RequiredArgument < self
  442.  
  443.       #
  444.       # Raises an exception if argument is not present.
  445.       #
  446.       def parse(arg, argv)
  447.         unless arg
  448.           raise MissingArgument if argv.empty?
  449.           arg = argv.shift
  450.         end
  451.         conv_arg(*parse_arg(arg) {|*exc| raise(*exc)})
  452.       end
  453.     end
  454.  
  455.     #
  456.     # Switch that can omit argument.
  457.     #
  458.     class OptionalArgument < self
  459.  
  460.       #
  461.       # Parses argument if given, or uses default value.
  462.       #
  463.       def parse(arg, argv, &error)
  464.         if arg
  465.           conv_arg(*parse_arg(arg, &error))
  466.         else
  467.           conv_arg(arg)
  468.         end
  469.       end
  470.     end
  471.  
  472.     #
  473.     # Switch that takes an argument, which does not begin with '-'.
  474.     #
  475.     class PlacedArgument < self
  476.  
  477.       #
  478.       # Returns nil if argument is not present or begins with '-'.
  479.       #
  480.       def parse(arg, argv, &error)
  481.         if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
  482.           return nil, block, nil
  483.         end
  484.         opt = (val = parse_arg(val, &error))[1]
  485.         val = conv_arg(*val)
  486.         if opt and !arg
  487.           argv.shift
  488.         else
  489.           val[0] = nil
  490.         end
  491.         val
  492.       end
  493.     end
  494.   end
  495.  
  496.   #
  497.   # Simple option list providing mapping from short and/or long option
  498.   # string to OptionParser::Switch and mapping from acceptable argument to
  499.   # matching pattern and converter pair. Also provides summary feature.
  500.   #
  501.   class List
  502.     # Map from acceptable argument types to pattern and converter pairs.
  503.     attr_reader :atype
  504.     
  505.     # Map from short style option switches to actual switch objects.
  506.     attr_reader :short
  507.     
  508.     # Map from long style option switches to actual switch objects.
  509.     attr_reader :long
  510.     
  511.     # List of all switches and summary string.
  512.     attr_reader :list
  513.  
  514.     #
  515.     # Just initializes all instance variables.
  516.     #
  517.     def initialize
  518.       @atype = {}
  519.       @short = OptionMap.new
  520.       @long = OptionMap.new
  521.       @list = []
  522.     end
  523.  
  524.     #
  525.     # See OptionParser.accept.
  526.     #
  527.     def accept(t, pat = /.*/nm, &block)
  528.       if pat
  529.         pat.respond_to?(:match) or raise TypeError, "has no `match'"
  530.       else
  531.         pat = t if t.respond_to?(:match)
  532.       end
  533.       unless block
  534.         block = pat.method(:convert).to_proc if pat.respond_to?(:convert)
  535.       end
  536.       @atype[t] = [pat, block]
  537.     end
  538.  
  539.     #
  540.     # See OptionParser.reject.
  541.     #
  542.     def reject(t)
  543.       @atype.delete(t)
  544.     end
  545.  
  546.     #
  547.     # Adds +sw+ according to +sopts+, +lopts+ and +nlopts+.
  548.     #
  549.     # +sw+::     OptionParser::Switch instance to be added.
  550.     # +sopts+::  Short style option list.
  551.     # +lopts+::  Long style option list.
  552.     # +nlopts+:: Negated long style options list.
  553.     #
  554.     def update(sw, sopts, lopts, nsw = nil, nlopts = nil)
  555.       o = nil
  556.       sopts.each {|o| @short[o] = sw} if sopts
  557.       lopts.each {|o| @long[o] = sw} if lopts
  558.       nlopts.each {|o| @long[o] = nsw} if nsw and nlopts
  559.       used = @short.invert.update(@long.invert)
  560.       @list.delete_if {|o| Switch === o and !used[o]}
  561.     end
  562.     private :update
  563.  
  564.     #
  565.     # Inserts +switch+ at the head of the list, and associates short, long
  566.     # and negated long options. Arguments are:
  567.     # 
  568.     # +switch+::      OptionParser::Switch instance to be inserted.
  569.     # +short_opts+::  List of short style options.
  570.     # +long_opts+::   List of long style options.
  571.     # +nolong_opts+:: List of long style options with "no-" prefix.
  572.     #
  573.     #   prepend(switch, short_opts, long_opts, nolong_opts)
  574.     #
  575.     def prepend(*args)
  576.       update(*args)
  577.       @list.unshift(args[0])
  578.     end
  579.  
  580.     #
  581.     # Appends +switch+ at the tail of the list, and associates short, long
  582.     # and negated long options. Arguments are:
  583.     # 
  584.     # +switch+::      OptionParser::Switch instance to be inserted.
  585.     # +short_opts+::  List of short style options.
  586.     # +long_opts+::   List of long style options.
  587.     # +nolong_opts+:: List of long style options with "no-" prefix.
  588.     #
  589.     #   append(switch, short_opts, long_opts, nolong_opts)
  590.     #
  591.     def append(*args)
  592.       update(*args)
  593.       @list.push(args[0])
  594.     end
  595.  
  596.     #
  597.     # Searches +key+ in +id+ list. The result is returned or yielded if a
  598.     # block is given. If it isn't found, nil is returned.
  599.     #
  600.     def search(id, key)
  601.       if list = __send__(id)
  602.         val = list.fetch(key) {return nil}
  603.         block_given? ? yield(val) : val
  604.       end
  605.     end
  606.  
  607.     #
  608.     # Searches list +id+ for +opt+ and the optional patterns for completion
  609.     # +pat+. If +icase+ is true, the search is case insensitive. The result
  610.     # is returned or yielded if a block is given. If it isn't found, nil is
  611.     # returned.
  612.     #
  613.     def complete(id, opt, icase = false, *pat, &block)
  614.       __send__(id).complete(opt, icase, *pat, &block)
  615.     end
  616.  
  617.     #
  618.     # Iterates over each option, passing the option to the +block+.
  619.     #
  620.     def each_option(&block)
  621.       list.each(&block)
  622.     end
  623.  
  624.     #
  625.     # Creates the summary table, passing each line to the +block+ (without
  626.     # newline). The arguments +args+ are passed along to the summarize
  627.     # method which is called on every option.
  628.     #
  629.     def summarize(*args, &block)
  630.       sum = []
  631.       list.reverse_each do |opt|
  632.         if opt.respond_to?(:summarize) # perhaps OptionParser::Switch
  633.           s = []
  634.           opt.summarize(*args) {|l| s << l}
  635.           sum.concat(s.reverse)
  636.         elsif !opt or opt.empty?
  637.           sum << ""
  638.         elsif opt.respond_to?(:each_line)
  639.           sum.concat([*opt.each_line].reverse)
  640.         else
  641.           sum.concat([*opt.each].reverse)
  642.         end
  643.       end
  644.       sum.reverse_each(&block)
  645.     end
  646.  
  647.     def add_banner(to)  # :nodoc:
  648.       list.each do |opt|
  649.         if opt.respond_to?(:add_banner)
  650.           opt.add_banner(to)
  651.         end
  652.       end
  653.       to
  654.     end
  655.   end
  656.  
  657.   #
  658.   # Hash with completion search feature. See OptionParser::Completion.
  659.   #
  660.   class CompletingHash < Hash
  661.     include Completion
  662.  
  663.     #
  664.     # Completion for hash key.
  665.     #
  666.     def match(key)
  667.       return key, *fetch(key) {
  668.         raise AmbiguousArgument, catch(:ambiguous) {return complete(key)}
  669.       }
  670.     end
  671.   end
  672.  
  673.   # :stopdoc:
  674.  
  675.   #
  676.   # Enumeration of acceptable argument styles. Possible values are:
  677.   #
  678.   # NO_ARGUMENT::       The switch takes no arguments. (:NONE)
  679.   # REQUIRED_ARGUMENT:: The switch requires an argument. (:REQUIRED)
  680.   # OPTIONAL_ARGUMENT:: The switch requires an optional argument. (:OPTIONAL)
  681.   #
  682.   # Use like --switch=argument (long style) or -Xargument (short style). For
  683.   # short style, only portion matched to argument pattern is dealed as
  684.   # argument.
  685.   #
  686.   ArgumentStyle = {}
  687.   NoArgument.each {|el| ArgumentStyle[el] = Switch::NoArgument}
  688.   RequiredArgument.each {|el| ArgumentStyle[el] = Switch::RequiredArgument}
  689.   OptionalArgument.each {|el| ArgumentStyle[el] = Switch::OptionalArgument}
  690.   ArgumentStyle.freeze
  691.  
  692.   #
  693.   # Switches common used such as '--', and also provides default
  694.   # argument classes
  695.   #
  696.   DefaultList = List.new
  697.   DefaultList.short['-'] = Switch::NoArgument.new {}
  698.   DefaultList.long[''] = Switch::NoArgument.new {throw :terminate}
  699.  
  700.   #
  701.   # Default options for ARGV, which never appear in option summary.
  702.   #
  703.   Officious = {}
  704.  
  705.   #
  706.   # --help
  707.   # Shows option summary.
  708.   #
  709.   Officious['help'] = proc do |parser|
  710.     Switch::NoArgument.new do
  711.       puts parser.help
  712.       exit
  713.     end
  714.   end
  715.  
  716.   #
  717.   # --version
  718.   # Shows version string if Version is defined.
  719.   #
  720.   Officious['version'] = proc do |parser|
  721.     Switch::OptionalArgument.new do |pkg|
  722.       if pkg
  723.         begin
  724.           require 'optparse/version'
  725.         rescue LoadError
  726.         else
  727.           show_version(*pkg.split(/,/)) or
  728.             abort("#{parser.program_name}: no version found in package #{pkg}")
  729.           exit
  730.         end
  731.       end
  732.       v = parser.ver or abort("#{parser.program_name}: version unknown")
  733.       puts v
  734.       exit
  735.     end
  736.   end
  737.  
  738.   # :startdoc:
  739.  
  740.   #
  741.   # Class methods
  742.   #
  743.  
  744.   #
  745.   # Initializes a new instance and evaluates the optional block in context
  746.   # of the instance. Arguments +args+ are passed to #new, see there for
  747.   # description of parameters.
  748.   # 
  749.   # This method is *deprecated*, its behavior corresponds to the older #new
  750.   # method.
  751.   #
  752.   def self.with(*args, &block)
  753.     opts = new(*args)
  754.     opts.instance_eval(&block)
  755.     opts
  756.   end
  757.  
  758.   #
  759.   # Returns an incremented value of +default+ according to +arg+.
  760.   #
  761.   def self.inc(arg, default = nil)
  762.     case arg
  763.     when Integer
  764.       arg.nonzero?
  765.     when nil
  766.       default.to_i + 1
  767.     end
  768.   end
  769.   def inc(*args)
  770.     self.class.inc(*args)
  771.   end
  772.  
  773.   #
  774.   # Initializes the instance and yields itself if called with a block.
  775.   #
  776.   # +banner+:: Banner message.
  777.   # +width+::  Summary width.
  778.   # +indent+:: Summary indent.
  779.   #
  780.   def initialize(banner = nil, width = 32, indent = ' ' * 4)
  781.     @stack = [DefaultList, List.new, List.new]
  782.     @program_name = nil
  783.     @banner = banner
  784.     @summary_width = width
  785.     @summary_indent = indent
  786.     @default_argv = ARGV
  787.     add_officious
  788.     yield self if block_given?
  789.   end
  790.  
  791.   def add_officious  # :nodoc:
  792.     list = base()
  793.     Officious.each do |opt, block|
  794.       list.long[opt] ||= block.call(self)
  795.     end
  796.   end
  797.  
  798.   #
  799.   # Terminates option parsing. Optional parameter +arg+ is a string pushed
  800.   # back to be the first non-option argument.
  801.   #
  802.   def terminate(arg = nil)
  803.     self.class.terminate(arg)
  804.   end
  805.   def self.terminate(arg = nil)
  806.     throw :terminate, arg
  807.   end
  808.  
  809.   @stack = [DefaultList]
  810.   def self.top() DefaultList end
  811.  
  812.   #
  813.   # Directs to accept specified class +t+. The argument string is passed to
  814.   # the block in which it should be converted to the desired class.
  815.   #
  816.   # +t+::   Argument class specifier, any object including Class.
  817.   # +pat+:: Pattern for argument, defaults to +t+ if it responds to match.
  818.   #
  819.   #   accept(t, pat, &block)
  820.   #
  821.   def accept(*args, &blk) top.accept(*args, &blk) end
  822.   #
  823.   # See #accept.
  824.   #
  825.   def self.accept(*args, &blk) top.accept(*args, &blk) end
  826.  
  827.   #
  828.   # Directs to reject specified class argument.
  829.   #
  830.   # +t+:: Argument class specifier, any object including Class.
  831.   #
  832.   #   reject(t)
  833.   #
  834.   def reject(*args, &blk) top.reject(*args, &blk) end
  835.   #
  836.   # See #reject.
  837.   #
  838.   def self.reject(*args, &blk) top.reject(*args, &blk) end
  839.  
  840.   #
  841.   # Instance methods
  842.   #
  843.  
  844.   # Heading banner preceding summary.
  845.   attr_writer :banner
  846.  
  847.   # Program name to be emitted in error message and default banner,
  848.   # defaults to $0.
  849.   attr_writer :program_name
  850.  
  851.   # Width for option list portion of summary. Must be Numeric.
  852.   attr_accessor :summary_width
  853.  
  854.   # Indentation for summary. Must be String (or have + String method).
  855.   attr_accessor :summary_indent
  856.  
  857.   # Strings to be parsed in default.
  858.   attr_accessor :default_argv
  859.  
  860.   #
  861.   # Heading banner preceding summary.
  862.   #
  863.   def banner
  864.     unless @banner
  865.       @banner = "Usage: #{program_name} [options]"
  866.       visit(:add_banner, @banner)
  867.     end
  868.     @banner
  869.   end
  870.  
  871.   #
  872.   # Program name to be emitted in error message and default banner, defaults
  873.   # to $0.
  874.   #
  875.   def program_name
  876.     @program_name || File.basename($0, '.*')
  877.   end
  878.  
  879.   # for experimental cascading :-)
  880.   alias set_banner banner=
  881.   alias set_program_name program_name=
  882.   alias set_summary_width summary_width=
  883.   alias set_summary_indent summary_indent=
  884.  
  885.   # Version
  886.   attr_writer :version
  887.   # Release code
  888.   attr_writer :release
  889.  
  890.   #
  891.   # Version
  892.   #
  893.   def version
  894.     @version || (defined?(::Version) && ::Version)
  895.   end
  896.  
  897.   #
  898.   # Release code
  899.   #
  900.   def release
  901.     @release || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE)
  902.   end
  903.  
  904.   #
  905.   # Returns version string from program_name, version and release.
  906.   #
  907.   def ver
  908.     if v = version
  909.       str = "#{program_name} #{[v].join('.')}"
  910.       str << " (#{v})" if v = release
  911.       str
  912.     end
  913.   end
  914.  
  915.   def warn(mesg = $!)
  916.     super("#{program_name}: #{mesg}")
  917.   end
  918.  
  919.   def abort(mesg = $!)
  920.     super("#{program_name}: #{mesg}")
  921.   end
  922.  
  923.   #
  924.   # Subject of #on / #on_head, #accept / #reject
  925.   #
  926.   def top
  927.     @stack[-1]
  928.   end
  929.  
  930.   #
  931.   # Subject of #on_tail.
  932.   #
  933.   def base
  934.     @stack[1]
  935.   end
  936.  
  937.   #
  938.   # Pushes a new List.
  939.   #
  940.   def new
  941.     @stack.push(List.new)
  942.     if block_given?
  943.       yield self
  944.     else
  945.       self
  946.     end
  947.   end
  948.  
  949.   #
  950.   # Removes the last List.
  951.   #
  952.   def remove
  953.     @stack.pop
  954.   end
  955.  
  956.   #
  957.   # Puts option summary into +to+ and returns +to+. Yields each line if
  958.   # a block is given.
  959.   #
  960.   # +to+:: Output destination, which must have method <<. Defaults to [].
  961.   # +width+:: Width of left side, defaults to @summary_width.
  962.   # +max+:: Maximum length allowed for left side, defaults to +width+ - 1.
  963.   # +indent+:: Indentation, defaults to @summary_indent.
  964.   #
  965.   def summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk)
  966.     blk ||= proc {|l| to << (l.index($/, -1) ? l : l + $/)}
  967.     visit(:summarize, {}, {}, width, max, indent, &blk)
  968.     to
  969.   end
  970.  
  971.   #
  972.   # Returns option summary string.
  973.   #
  974.   def help; summarize(banner.to_s.sub(/\n?\z/, "\n")) end
  975.   alias to_s help
  976.  
  977.   #
  978.   # Returns option summary list.
  979.   #
  980.   def to_a; summarize(banner.to_a.dup) end
  981.  
  982.   #
  983.   # Checks if an argument is given twice, in which case an ArgumentError is
  984.   # raised. Called from OptionParser#switch only.
  985.   #
  986.   # +obj+:: New argument.
  987.   # +prv+:: Previously specified argument.
  988.   # +msg+:: Exception message.
  989.   #
  990.   def notwice(obj, prv, msg)
  991.     unless !prv or prv == obj
  992.       begin
  993.         raise ArgumentError, "argument #{msg} given twice: #{obj}"
  994.       rescue
  995.         $@[0, 2] = nil
  996.         raise
  997.       end
  998.     end
  999.     obj
  1000.   end
  1001.   private :notwice
  1002.  
  1003.   #
  1004.   # Creates an OptionParser::Switch from the parameters. The parsed argument
  1005.   # value is passed to the given block, where it can be processed.
  1006.   #
  1007.   # See at the beginning of OptionParser for some full examples.
  1008.   #
  1009.   # +opts+ can include the following elements:
  1010.   #
  1011.   # [Argument style:]
  1012.   #   One of the following:
  1013.   #     :NONE, :REQUIRED, :OPTIONAL
  1014.   #
  1015.   # [Argument pattern:]
  1016.   #   Acceptable option argument format, must be pre-defined with
  1017.   #   OptionParser.accept or OptionParser#accept, or Regexp. This can appear
  1018.   #   once or assigned as String if not present, otherwise causes an
  1019.   #   ArgumentError. Examples:
  1020.   #     Float, Time, Array
  1021.   #
  1022.   # [Possible argument values:]
  1023.   #   Hash or Array.
  1024.   #     [:text, :binary, :auto]
  1025.   #     %w[iso-2022-jp shift_jis euc-jp utf8 binary]
  1026.   #     { "jis" => "iso-2022-jp", "sjis" => "shift_jis" }
  1027.   #
  1028.   # [Long style switch:]
  1029.   #   Specifies a long style switch which takes a mandatory, optional or no
  1030.   #   argument. It's a string of the following form:
  1031.   #     "--switch=MANDATORY" or "--switch MANDATORY"
  1032.   #     "--switch[=OPTIONAL]"
  1033.   #     "--switch"
  1034.   #
  1035.   # [Short style switch:]
  1036.   #   Specifies short style switch which takes a mandatory, optional or no
  1037.   #   argument. It's a string of the following form:
  1038.   #     "-xMANDATORY"
  1039.   #     "-x[OPTIONAL]"
  1040.   #     "-x"
  1041.   #   There is also a special form which matches character range (not full
  1042.   #   set of regular expression):
  1043.   #     "-[a-z]MANDATORY"
  1044.   #     "-[a-z][OPTIONAL]" 
  1045.   #     "-[a-z]"
  1046.   #
  1047.   # [Argument style and description:]
  1048.   #   Instead of specifying mandatory or optional arguments directly in the
  1049.   #   switch parameter, this separate parameter can be used.
  1050.   #     "=MANDATORY"
  1051.   #     "=[OPTIONAL]"
  1052.   #
  1053.   # [Description:]
  1054.   #   Description string for the option.
  1055.   #     "Run verbosely"
  1056.   # 
  1057.   # [Handler:]
  1058.   #   Handler for the parsed argument value. Either give a block or pass a
  1059.   #   Proc or Method as an argument.
  1060.   #
  1061.   def make_switch(opts, block = nil)
  1062.     short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], []
  1063.     ldesc, sdesc, desc, arg = [], [], []
  1064.     default_style = Switch::NoArgument
  1065.     default_pattern = nil
  1066.     klass = nil
  1067.     o = nil
  1068.     n, q, a = nil
  1069.  
  1070.     opts.each do |o|
  1071.       # argument class
  1072.       next if search(:atype, o) do |pat, c|
  1073.         klass = notwice(o, klass, 'type')
  1074.         if not_style and not_style != Switch::NoArgument
  1075.           not_pattern, not_conv = pat, c
  1076.         else
  1077.           default_pattern, conv = pat, c
  1078.         end
  1079.       end
  1080.  
  1081.       # directly specified pattern(any object possible to match)
  1082.       if !(String === o) and o.respond_to?(:match)
  1083.         pattern = notwice(o, pattern, 'pattern')
  1084.         conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert)
  1085.         next
  1086.       end
  1087.  
  1088.       # anything others
  1089.       case o
  1090.       when Proc, Method
  1091.         block = notwice(o, block, 'block')
  1092.       when Array, Hash
  1093.         case pattern
  1094.         when CompletingHash
  1095.         when nil
  1096.           pattern = CompletingHash.new
  1097.           conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert)
  1098.         else
  1099.           raise ArgumentError, "argument pattern given twice"
  1100.         end
  1101.         o.each {|(o, *v)| pattern[o] = v.fetch(0) {o}}
  1102.       when Module
  1103.         raise ArgumentError, "unsupported argument type: #{o}"
  1104.       when *ArgumentStyle.keys
  1105.         style = notwice(ArgumentStyle[o], style, 'style')
  1106.       when /^--no-([^\[\]=\s]*)(.+)?/
  1107.         q, a = $1, $2
  1108.         o = notwice(a ? Object : TrueClass, klass, 'type')
  1109.         not_pattern, not_conv = search(:atype, o) unless not_style
  1110.         not_style = (not_style || default_style).guess(arg = a) if a
  1111.         default_style = Switch::NoArgument
  1112.         default_pattern, conv = search(:atype, FalseClass) unless default_pattern
  1113.         ldesc << "--no-#{q}"
  1114.         long << 'no-' + (q = q.downcase)
  1115.         nolong << q
  1116.       when /^--\[no-\]([^\[\]=\s]*)(.+)?/
  1117.         q, a = $1, $2
  1118.         o = notwice(a ? Object : TrueClass, klass, 'type')
  1119.         if a
  1120.           default_style = default_style.guess(arg = a)
  1121.           default_pattern, conv = search(:atype, o) unless default_pattern
  1122.         end
  1123.         ldesc << "--[no-]#{q}"
  1124.         long << (o = q.downcase)
  1125.         not_pattern, not_conv = search(:atype, FalseClass) unless not_style
  1126.         not_style = Switch::NoArgument
  1127.         nolong << 'no-' + o
  1128.       when /^--([^\[\]=\s]*)(.+)?/
  1129.         q, a = $1, $2
  1130.         if a
  1131.           o = notwice(NilClass, klass, 'type')
  1132.           default_style = default_style.guess(arg = a)
  1133.           default_pattern, conv = search(:atype, o) unless default_pattern
  1134.         end
  1135.         ldesc << "--#{q}"
  1136.         long << (o = q.downcase)
  1137.       when /^-(\[\^?\]?(?:[^\\\]]|\\.)*\])(.+)?/
  1138.         q, a = $1, $2
  1139.         o = notwice(Object, klass, 'type')
  1140.         if a
  1141.           default_style = default_style.guess(arg = a)
  1142.           default_pattern, conv = search(:atype, o) unless default_pattern
  1143.         end
  1144.         sdesc << "-#{q}"
  1145.         short << Regexp.new(q)
  1146.       when /^-(.)(.+)?/
  1147.         q, a = $1, $2
  1148.         if a
  1149.           o = notwice(NilClass, klass, 'type')
  1150.           default_style = default_style.guess(arg = a)
  1151.           default_pattern, conv = search(:atype, o) unless default_pattern
  1152.         end
  1153.         sdesc << "-#{q}"
  1154.         short << q
  1155.       when /^=/
  1156.         style = notwice(default_style.guess(arg = o), style, 'style')
  1157.         default_pattern, conv = search(:atype, Object) unless default_pattern
  1158.       else
  1159.         desc.push(o)
  1160.       end
  1161.     end
  1162.  
  1163.     default_pattern, conv = search(:atype, default_style.pattern) unless default_pattern
  1164.     if !(short.empty? and long.empty?)
  1165.       s = (style || default_style).new(pattern || default_pattern,
  1166.                                        conv, sdesc, ldesc, arg, desc, block)
  1167.     elsif !block
  1168.       raise ArgumentError, "no switch given" if style or pattern
  1169.       s = desc
  1170.     else
  1171.       short << pattern
  1172.       s = (style || default_style).new(pattern,
  1173.                                        conv, nil, nil, arg, desc, block)
  1174.     end
  1175.     return s, short, long,
  1176.       (not_style.new(not_pattern, not_conv, sdesc, ldesc, nil, desc, block) if not_style),
  1177.       nolong
  1178.   end
  1179.  
  1180.   def define(*opts, &block)
  1181.     top.append(*(sw = make_switch(opts, block)))
  1182.     sw[0]
  1183.   end
  1184.  
  1185.   #
  1186.   # Add option switch and handler. See #make_switch for an explanation of
  1187.   # parameters.
  1188.   #
  1189.   def on(*opts, &block)
  1190.     define(*opts, &block)
  1191.     self
  1192.   end
  1193.   alias def_option define
  1194.  
  1195.   def define_head(*opts, &block)
  1196.     top.prepend(*(sw = make_switch(opts, block)))
  1197.     sw[0]
  1198.   end
  1199.  
  1200.   #
  1201.   # Add option switch like with #on, but at head of summary.
  1202.   #
  1203.   def on_head(*opts, &block)
  1204.     define_head(*opts, &block)
  1205.     self
  1206.   end
  1207.   alias def_head_option define_head
  1208.  
  1209.   def define_tail(*opts, &block)
  1210.     base.append(*(sw = make_switch(opts, block)))
  1211.     sw[0]
  1212.   end
  1213.  
  1214.   #
  1215.   # Add option switch like with #on, but at tail of summary.
  1216.   #
  1217.   def on_tail(*opts, &block)
  1218.     define_tail(*opts, &block)
  1219.     self
  1220.   end
  1221.   alias def_tail_option define_tail
  1222.  
  1223.   #
  1224.   # Add separator in summary.
  1225.   #
  1226.   def separator(string)
  1227.     top.append(string, nil, nil)
  1228.   end
  1229.  
  1230.   #
  1231.   # Parses command line arguments +argv+ in order. When a block is given,
  1232.   # each non-option argument is yielded.
  1233.   #
  1234.   # Returns the rest of +argv+ left unparsed.
  1235.   #
  1236.   def order(*argv, &block)
  1237.     argv = argv[0].dup if argv.size == 1 and Array === argv[0]
  1238.     order!(argv, &block)
  1239.   end
  1240.  
  1241.   #
  1242.   # Same as #order, but removes switches destructively.
  1243.   #
  1244.   def order!(argv = default_argv, &nonopt)
  1245.     parse_in_order(argv, &nonopt)
  1246.   end
  1247.  
  1248.   def parse_in_order(argv = default_argv, setter = nil, &nonopt)  # :nodoc:
  1249.     opt, arg, sw, val, rest = nil
  1250.     nonopt ||= proc {|arg| throw :terminate, arg}
  1251.     argv.unshift(arg) if arg = catch(:terminate) {
  1252.       while arg = argv.shift
  1253.         case arg
  1254.         # long option
  1255.         when /\A--([^=]*)(?:=(.*))?/nm
  1256.           opt, rest = $1, $2
  1257.           begin
  1258.             sw, = complete(:long, opt, true)
  1259.           rescue ParseError
  1260.             raise $!.set_option(arg, true)
  1261.           end
  1262.           begin
  1263.             opt, cb, val = sw.parse(rest, argv) {|*exc| raise(*exc)}
  1264.             val = cb.call(val) if cb
  1265.             setter.call(sw.switch_name, val) if setter
  1266.           rescue ParseError
  1267.             raise $!.set_option(arg, rest)
  1268.           end
  1269.  
  1270.         # short option
  1271.         when /\A-(.)((=).*|.+)?/nm
  1272.           opt, has_arg, eq, val, rest = $1, $3, $3, $2, $2
  1273.           begin
  1274.             sw, = search(:short, opt)
  1275.             unless sw
  1276.               begin
  1277.                 sw, = complete(:short, opt)
  1278.                 # short option matched.
  1279.                 val = arg.sub(/\A-/, '')
  1280.                 has_arg = true
  1281.               rescue InvalidOption
  1282.                 # if no short options match, try completion with long
  1283.                 # options.
  1284.                 sw, = complete(:long, opt)
  1285.                 eq ||= !rest
  1286.               end
  1287.             end
  1288.           rescue ParseError
  1289.             raise $!.set_option(arg, true)
  1290.           end
  1291.           begin
  1292.             opt, cb, val = sw.parse(val, argv) {|*exc| raise(*exc) if eq}
  1293.             raise InvalidOption, arg if has_arg and !eq and arg == "-#{opt}"
  1294.             argv.unshift(opt) if opt and (opt = opt.sub(/\A-*/, '-')) != '-'
  1295.             val = cb.call(val) if cb
  1296.             setter.call(sw.switch_name, val) if setter
  1297.           rescue ParseError
  1298.             raise $!.set_option(arg, arg.length > 2)
  1299.           end
  1300.  
  1301.         # non-option argument
  1302.         else
  1303.           catch(:prune) do
  1304.             visit(:each_option) do |sw|
  1305.               sw.block.call(arg) if Switch === sw and sw.match_nonswitch?(arg)
  1306.             end
  1307.             nonopt.call(arg)
  1308.           end
  1309.         end
  1310.       end
  1311.  
  1312.       nil
  1313.     }
  1314.  
  1315.     visit(:search, :short, nil) {|sw| sw.block.call(*argv) if !sw.pattern}
  1316.  
  1317.     argv
  1318.   end
  1319.   private :parse_in_order
  1320.  
  1321.   #
  1322.   # Parses command line arguments +argv+ in permutation mode and returns
  1323.   # list of non-option arguments.
  1324.   #
  1325.   def permute(*argv)
  1326.     argv = argv[0].dup if argv.size == 1 and Array === argv[0]
  1327.     permute!(argv)
  1328.   end
  1329.  
  1330.   #
  1331.   # Same as #permute, but removes switches destructively.
  1332.   #
  1333.   def permute!(argv = default_argv)
  1334.     nonopts = []
  1335.     arg = nil
  1336.     order!(argv) {|arg| nonopts << arg}
  1337.     argv[0, 0] = nonopts
  1338.     argv
  1339.   end
  1340.  
  1341.   #
  1342.   # Parses command line arguments +argv+ in order when environment variable
  1343.   # POSIXLY_CORRECT is set, and in permutation mode otherwise.
  1344.   #
  1345.   def parse(*argv)
  1346.     argv = argv[0].dup if argv.size == 1 and Array === argv[0]
  1347.     parse!(argv)
  1348.   end
  1349.  
  1350.   #
  1351.   # Same as #parse, but removes switches destructively.
  1352.   #
  1353.   def parse!(argv = default_argv)
  1354.     if ENV.include?('POSIXLY_CORRECT')
  1355.       order!(argv)
  1356.     else
  1357.       permute!(argv)
  1358.     end
  1359.   end
  1360.  
  1361.   #
  1362.   # Wrapper method for getopts.rb.
  1363.   #
  1364.   #   params = ARGV.getopts("ab:", "foo", "bar:")
  1365.   #   # params[:a] = true   # -a
  1366.   #   # params[:b] = "1"    # -b1
  1367.   #   # params[:foo] = "1"  # --foo
  1368.   #   # params[:bar] = "x"  # --bar x
  1369.   #
  1370.   def getopts(*args)
  1371.     argv = Array === args.first ? args.shift : default_argv
  1372.     single_options, *long_options = *args
  1373.  
  1374.     result = {}
  1375.  
  1376.     single_options.scan(/(.)(:)?/) do |opt, val|
  1377.       if val
  1378.         result[opt] = nil
  1379.         define("-#{opt} VAL")
  1380.       else
  1381.         result[opt] = false
  1382.         define("-#{opt}")
  1383.       end
  1384.     end if single_options
  1385.  
  1386.     long_options.each do |arg|
  1387.       opt, val = arg.split(':', 2)
  1388.       if val
  1389.         result[opt] = val.empty? ? nil : val
  1390.         define("--#{opt} VAL")
  1391.       else
  1392.         result[opt] = false
  1393.         define("--#{opt}")
  1394.       end
  1395.     end
  1396.  
  1397.     parse_in_order(argv, result.method(:[]=))
  1398.     result
  1399.   end
  1400.  
  1401.   #
  1402.   # See #getopts.
  1403.   #
  1404.   def self.getopts(*args)
  1405.     new.getopts(*args)
  1406.   end
  1407.  
  1408.   #
  1409.   # Traverses @stack, sending each element method +id+ with +args+ and
  1410.   # +block+.
  1411.   #
  1412.   def visit(id, *args, &block)
  1413.     el = nil
  1414.     @stack.reverse_each do |el|
  1415.       el.send(id, *args, &block)
  1416.     end
  1417.     nil
  1418.   end
  1419.   private :visit
  1420.  
  1421.   #
  1422.   # Searches +key+ in @stack for +id+ hash and returns or yields the result.
  1423.   #
  1424.   def search(id, key)
  1425.     block_given = block_given?
  1426.     visit(:search, id, key) do |k|
  1427.       return block_given ? yield(k) : k
  1428.     end
  1429.   end
  1430.   private :search
  1431.  
  1432.   #
  1433.   # Completes shortened long style option switch and returns pair of
  1434.   # canonical switch and switch descriptor OptionParser::Switch.
  1435.   #
  1436.   # +id+::    Searching table.
  1437.   # +opt+::   Searching key.
  1438.   # +icase+:: Search case insensitive if true.
  1439.   # +pat+::   Optional pattern for completion.
  1440.   #
  1441.   def complete(typ, opt, icase = false, *pat)
  1442.     if pat.empty?
  1443.       search(typ, opt) {|sw| return [sw, opt]} # exact match or...
  1444.     end
  1445.     raise AmbiguousOption, catch(:ambiguous) {
  1446.       visit(:complete, typ, opt, icase, *pat) {|opt, *sw| return sw}
  1447.       raise InvalidOption, opt
  1448.     }
  1449.   end
  1450.   private :complete
  1451.  
  1452.   #
  1453.   # Loads options from file names as +filename+. Does nothing when the file
  1454.   # is not present. Returns whether successfully loaded.
  1455.   #
  1456.   # +filename+ defaults to basename of the program without suffix in a
  1457.   # directory ~/.options.
  1458.   #
  1459.   def load(filename = nil)
  1460.     begin
  1461.       filename ||= File.expand_path(File.basename($0, '.*'), '~/.options')
  1462.     rescue
  1463.       return false
  1464.     end
  1465.     begin
  1466.       parse(*IO.readlines(filename).each {|s| s.chomp!})
  1467.       true
  1468.     rescue Errno::ENOENT, Errno::ENOTDIR
  1469.       false
  1470.     end
  1471.   end
  1472.  
  1473.   #
  1474.   # Parses environment variable +env+ or its uppercase with splitting like a
  1475.   # shell.
  1476.   #
  1477.   # +env+ defaults to the basename of the program.
  1478.   #
  1479.   def environment(env = File.basename($0, '.*'))
  1480.     env = ENV[env] || ENV[env.upcase] or return
  1481.     require 'shellwords'
  1482.     parse(*Shellwords.shellwords(env))
  1483.   end
  1484.  
  1485.   #
  1486.   # Acceptable argument classes
  1487.   #
  1488.  
  1489.   #
  1490.   # Any string and no conversion. This is fall-back.
  1491.   #
  1492.   accept(Object) {|s,|s or s.nil?}
  1493.  
  1494.   accept(NilClass) {|s,|s}
  1495.  
  1496.   #
  1497.   # Any non-empty string, and no conversion.
  1498.   #
  1499.   accept(String, /.+/nm) {|s,*|s}
  1500.  
  1501.   #
  1502.   # Ruby/C-like integer, octal for 0-7 sequence, binary for 0b, hexadecimal
  1503.   # for 0x, and decimal for others; with optional sign prefix. Converts to
  1504.   # Integer.
  1505.   #
  1506.   decimal = '\d+(?:_\d+)*'
  1507.   binary = 'b[01]+(?:_[01]+)*'
  1508.   hex = 'x[\da-f]+(?:_[\da-f]+)*'
  1509.   octal = "0(?:[0-7]*(?:_[0-7]+)*|#{binary}|#{hex})"
  1510.   integer = "#{octal}|#{decimal}"
  1511.   accept(Integer, %r"\A[-+]?(?:#{integer})"io) {|s,| Integer(s) if s}
  1512.  
  1513.   #
  1514.   # Float number format, and converts to Float.
  1515.   #
  1516.   float = "(?:#{decimal}(?:\\.(?:#{decimal})?)?|\\.#{decimal})(?:E[-+]?#{decimal})?"
  1517.   floatpat = %r"\A[-+]?#{float}"io
  1518.   accept(Float, floatpat) {|s,| s.to_f if s}
  1519.  
  1520.   #
  1521.   # Generic numeric format, converts to Integer for integer format, Float
  1522.   # for float format.
  1523.   #
  1524.   accept(Numeric, %r"\A[-+]?(?:#{octal}|#{float})"io) {|s,| eval(s) if s}
  1525.  
  1526.   #
  1527.   # Decimal integer format, to be converted to Integer.
  1528.   #
  1529.   DecimalInteger = /\A[-+]?#{decimal}/io
  1530.   accept(DecimalInteger) {|s,| s.to_i if s}
  1531.  
  1532.   #
  1533.   # Ruby/C like octal/hexadecimal/binary integer format, to be converted to
  1534.   # Integer.
  1535.   #
  1536.   OctalInteger = /\A[-+]?(?:[0-7]+(?:_[0-7]+)*|0(?:#{binary}|#{hex}))/io
  1537.   accept(OctalInteger) {|s,| s.oct if s}
  1538.  
  1539.   #
  1540.   # Decimal integer/float number format, to be converted to Integer for
  1541.   # integer format, Float for float format.
  1542.   #
  1543.   DecimalNumeric = floatpat     # decimal integer is allowed as float also.
  1544.   accept(DecimalNumeric) {|s,| eval(s) if s}
  1545.  
  1546.   #
  1547.   # Boolean switch, which means whether it is present or not, whether it is
  1548.   # absent or not with prefix no-, or it takes an argument
  1549.   # yes/no/true/false/+/-.
  1550.   #
  1551.   yesno = CompletingHash.new
  1552.   %w[- no false].each {|el| yesno[el] = false}
  1553.   %w[+ yes true].each {|el| yesno[el] = true}
  1554.   yesno['nil'] = false          # shoud be nil?
  1555.   accept(TrueClass, yesno) {|arg, val| val == nil or val}
  1556.   #
  1557.   # Similar to TrueClass, but defaults to false.
  1558.   #
  1559.   accept(FalseClass, yesno) {|arg, val| val != nil and val}
  1560.  
  1561.   #
  1562.   # List of strings separated by ",".
  1563.   #
  1564.   accept(Array) do |s,|
  1565.     if s
  1566.       s = s.split(',').collect {|s| s unless s.empty?}
  1567.     end
  1568.     s
  1569.   end
  1570.  
  1571.   #
  1572.   # Regular expression with options.
  1573.   #
  1574.   accept(Regexp, %r"\A/((?:\\.|[^\\])*)/([[:alpha:]]+)?\z|.*") do |all, s, o|
  1575.     f = 0
  1576.     if o
  1577.       f |= Regexp::IGNORECASE if /i/ =~ o
  1578.       f |= Regexp::MULTILINE if /m/ =~ o
  1579.       f |= Regexp::EXTENDED if /x/ =~ o
  1580.       k = o.delete("^imx")
  1581.     end
  1582.     Regexp.new(s || all, f, k)
  1583.   end
  1584.  
  1585.   #
  1586.   # Exceptions
  1587.   #
  1588.  
  1589.   #
  1590.   # Base class of exceptions from OptionParser.
  1591.   #
  1592.   class ParseError < RuntimeError
  1593.     # Reason which caused the error.
  1594.     Reason = 'parse error'.freeze
  1595.  
  1596.     def initialize(*args)
  1597.       @args = args
  1598.       @reason = nil
  1599.     end
  1600.  
  1601.     attr_reader :args
  1602.     attr_writer :reason
  1603.  
  1604.     #
  1605.     # Pushes back erred argument(s) to +argv+.
  1606.     #
  1607.     def recover(argv)
  1608.       argv[0, 0] = @args
  1609.       argv
  1610.     end
  1611.  
  1612.     def set_option(opt, eq)
  1613.       if eq
  1614.         @args[0] = opt
  1615.       else
  1616.         @args.unshift(opt)
  1617.       end
  1618.       self
  1619.     end
  1620.  
  1621.     #
  1622.     # Returns error reason. Override this for I18N.
  1623.     #
  1624.     def reason
  1625.       @reason || self.class::Reason
  1626.     end
  1627.  
  1628.     def inspect
  1629.       "#<#{self.class.to_s}: #{args.join(' ')}>"
  1630.     end
  1631.  
  1632.     #
  1633.     # Default stringizing method to emit standard error message.
  1634.     #
  1635.     def message
  1636.       reason + ': ' + args.join(' ')
  1637.     end
  1638.  
  1639.     alias to_s message
  1640.   end
  1641.  
  1642.   #
  1643.   # Raises when ambiguously completable string is encountered.
  1644.   #
  1645.   class AmbiguousOption < ParseError
  1646.     const_set(:Reason, 'ambiguous option'.freeze)
  1647.   end
  1648.  
  1649.   #
  1650.   # Raises when there is an argument for a switch which takes no argument.
  1651.   #
  1652.   class NeedlessArgument < ParseError
  1653.     const_set(:Reason, 'needless argument'.freeze)
  1654.   end
  1655.  
  1656.   #
  1657.   # Raises when a switch with mandatory argument has no argument.
  1658.   #
  1659.   class MissingArgument < ParseError
  1660.     const_set(:Reason, 'missing argument'.freeze)
  1661.   end
  1662.  
  1663.   #
  1664.   # Raises when switch is undefined.
  1665.   #
  1666.   class InvalidOption < ParseError
  1667.     const_set(:Reason, 'invalid option'.freeze)
  1668.   end
  1669.  
  1670.   #
  1671.   # Raises when the given argument does not match required format.
  1672.   #
  1673.   class InvalidArgument < ParseError
  1674.     const_set(:Reason, 'invalid argument'.freeze)
  1675.   end
  1676.  
  1677.   #
  1678.   # Raises when the given argument word can't be completed uniquely.
  1679.   #
  1680.   class AmbiguousArgument < InvalidArgument
  1681.     const_set(:Reason, 'ambiguous argument'.freeze)
  1682.   end
  1683.  
  1684.   #
  1685.   # Miscellaneous
  1686.   #
  1687.  
  1688.   #
  1689.   # Extends command line arguments array (ARGV) to parse itself.
  1690.   #
  1691.   module Arguable
  1692.  
  1693.     #
  1694.     # Sets OptionParser object, when +opt+ is +false+ or +nil+, methods
  1695.     # OptionParser::Arguable#options and OptionParser::Arguable#options= are
  1696.     # undefined. Thus, there is no ways to access the OptionParser object
  1697.     # via the receiver object.
  1698.     #
  1699.     def options=(opt)
  1700.       unless @optparse = opt
  1701.         class << self
  1702.           undef_method(:options)
  1703.           undef_method(:options=)
  1704.         end
  1705.       end
  1706.     end
  1707.  
  1708.     #
  1709.     # Actual OptionParser object, automatically created if nonexistent.
  1710.     #
  1711.     # If called with a block, yields the OptionParser object and returns the
  1712.     # result of the block. If an OptionParser::ParseError exception occurs
  1713.     # in the block, it is rescued, a error message printed to STDERR and
  1714.     # +nil+ returned.
  1715.     #
  1716.     def options
  1717.       @optparse ||= OptionParser.new
  1718.       @optparse.default_argv = self
  1719.       block_given? or return @optparse
  1720.       begin
  1721.         yield @optparse
  1722.       rescue ParseError
  1723.         @optparse.warn $!
  1724.         nil
  1725.       end
  1726.     end
  1727.  
  1728.     #
  1729.     # Parses +self+ destructively in order and returns +self+ containing the
  1730.     # rest arguments left unparsed.
  1731.     #
  1732.     def order!(&blk) options.order!(self, &blk) end
  1733.  
  1734.     #
  1735.     # Parses +self+ destructively in permutation mode and returns +self+
  1736.     # containing the rest arguments left unparsed.
  1737.     #
  1738.     def permute!() options.permute!(self) end
  1739.  
  1740.     #
  1741.     # Parses +self+ destructively and returns +self+ containing the
  1742.     # rest arguments left unparsed.
  1743.     #
  1744.     def parse!() options.parse!(self) end
  1745.  
  1746.     #
  1747.     # Substitution of getopts is possible as follows. Also see
  1748.     # OptionParser#getopts.
  1749.     #
  1750.     #   def getopts(*args)
  1751.     #     ($OPT = ARGV.getopts(*args)).each do |opt, val|
  1752.     #       eval "$OPT_#{opt.gsub(/[^A-Za-z0-9_]/, '_')} = val"
  1753.     #     end
  1754.     #   rescue OptionParser::ParseError
  1755.     #   end
  1756.     #
  1757.     def getopts(*args)
  1758.       options.getopts(self, *args)
  1759.     end
  1760.  
  1761.     #
  1762.     # Initializes instance variable.
  1763.     #
  1764.     def self.extend_object(obj)
  1765.       super
  1766.       obj.instance_eval {@optparse = nil}
  1767.     end
  1768.     def initialize(*args)
  1769.       super
  1770.       @optparse = nil
  1771.     end
  1772.   end
  1773.  
  1774.   #
  1775.   # Acceptable argument classes. Now contains DecimalInteger, OctalInteger
  1776.   # and DecimalNumeric. See Acceptable argument classes (in source code).
  1777.   #
  1778.   module Acceptables
  1779.     const_set(:DecimalInteger, OptionParser::DecimalInteger)
  1780.     const_set(:OctalInteger, OptionParser::OctalInteger)
  1781.     const_set(:DecimalNumeric, OptionParser::DecimalNumeric)
  1782.   end
  1783. end
  1784.  
  1785. # ARGV is arguable by OptionParser
  1786. ARGV.extend(OptionParser::Arguable)
  1787.  
  1788. if $0 == __FILE__
  1789.   Version = OptionParser::Version
  1790.   ARGV.options {|q|
  1791.     q.parse!.empty? or puts "what's #{ARGV.join(' ')}?"
  1792.   } or abort(ARGV.options.to_s)
  1793. end
  1794.